﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using WP.Modules;
using WP.DB;
using WP.Controls;
using WP.Commons;
using System.Collections;


namespace WP.IM.Form
{
    public partial class frmImInvMaster : BaseMtn 
    {
        public frmImInvMaster()
        {
            InitializeComponent();
            LoadAllControl(new ArrayList(this.Controls));
            this.MtnTabControl = this.tbcMain;
            this.DesignTabsName = "tbpGeneral";
            tbcMain.DrawMode = TabDrawMode.OwnerDrawFixed;
            this.MinimumSize = this.Size;
        }

        #region Define Variable
        private bool mblnSettingStatus = false;
        #endregion

        #region ***Form Events

        private void frmImItemMaster_Load(object sender, EventArgs e)
        {
            this.TableName = "imInvMaster";
            //dgList.ColumnWidth = "0,70,180,100,40,20,120,90,130";
            dgList.ConnectionString = DBAccess.ConnectionDBString;
            dgList.TableName = this.TableName;
            dgList.ColumnWidth = DataFunctions.GetGridColumnWidthString(this.Name, this.CurrentMenuInfo.iParameter, SysVar.UserName, this.Name + "." + this.dgList.Name);
            string strSql = WP.Commons.BaseFunctions.GetLookUpSQL(this.TableName, this.CurrentMenuInfo.iParameter);
            dgList.Sql = strSql;
            this.formStatus = FormStatus.Query;

            FillLookUpInfo();
            initMaterialType();
            InitSecondMaterialType(); 
        }


        private  void initMaterialType()
        {
            tsCboMaterialType.Items.Clear();
            string strSQL = "";
            DBAccess dbcon = new DBAccess(false, false);
            tsCboMaterialType.Items.Add("");
            strSQL = "select distinct materialtypeID,materialtype from rmMaterialType order by materialTypeID,materialtype";
            DataTable dtType = dbcon.GetDataTable(strSQL);
            foreach (DataRow drRow in dtType.Rows)
            {
                tsCboMaterialType.Items.Add(CvtFunc.ToString(drRow["materialtypeID"]) + " - " + CvtFunc.ToString(drRow["materialtype"]));
            }
            dbcon.CloseCon();
        }

        private void InitSecondMaterialType()
        {
            tsCboSecondMaterialType.Items.Clear();
            tsCboSecondMaterialType.SelectedItem = "";
            tsCboSecondMaterialType.Text = "";
            string strSQL = "";
            tsCboSecondMaterialType.Items.Add("");
            DBAccess dbcon = new DBAccess(false, false);
            //string strParentMaterialID = DataFunctions.GetFieldValue("rmMaterialType", "materialtypeID", "materialtype='" + strParentMaterialType + "'");
            strSQL = "select distinct MaterialTypeID,MaterialTypeName from rmSecondMaterialType order by MaterialTypeID,MaterialTypeName";
            DataTable dtType = dbcon.GetDataTable(strSQL);
            foreach (DataRow drRow in dtType.Rows)
            {
                tsCboSecondMaterialType.Items.Add(CvtFunc.ToString(drRow["MaterialTypeID"]) + " - " + CvtFunc.ToString(drRow["MaterialTypeName"]));
            }
            dbcon.CloseCon();

        }

        private void frmImItemMaster_FormClosing(object sender, FormClosingEventArgs e)
        {
            DataFunctions.SetGridColumnWidthString(this.Name, this.CurrentMenuInfo.iParameter, SysVar.UserName, this.dgList);
        }
        private void btnUpdate_Click(object sender, EventArgs e)
        {
            if (!this.UpdateData()) return;
            base.SetStatusAfterUpdate();
        }
        private void btnNew_Click(object sender, EventArgs e)
        {
            if (this.ConfirmChange())
            {
                if (!this.UpdateData()) return;
            }
            this.formStatus = FormStatus.AddNew;
        }
        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (!this.DeleteData()) return;
        }
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.formStatus = FormStatus.Delete;
        }
        private void btnExit_Click(object sender, EventArgs e)
        {
            if (this.formStatus == FormStatus.AddNew || this.formStatus == FormStatus.Update)
            {
                if (this.ConfirmChange())
                {
                    if (MessageBox.Show(SysVar.SaveChangeTitle, SysVar.WarnTitle, MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        if (!this.UpdateData()) return;
                    }
                }
            }
            this.ExitingStatus = true;
            this.Close();
        }
        private void btnHelp_Click(object sender, EventArgs e)
        {
            base.OnHelp();
        }
        private void btnToExcel_Click(object sender, EventArgs e)
        {
            base.ExportToExcel(dgList);
        }
        private void btnNext_Click(object sender, EventArgs e)
        {
            Nevigate(this.dgList, NavigateOrient.Next);
        }
        private void btnPrev_Click(object sender, EventArgs e)
        {
            Nevigate(this.dgList, NavigateOrient.Prev);
        }
        private void btnTop_Click(object sender, EventArgs e)
        {
            Nevigate(this.dgList, NavigateOrient.Top);
        }
        private void btnBottom_Click(object sender, EventArgs e)
        {
            Nevigate(this.dgList, NavigateOrient.Bottom);
        }
        public override void SetNavigatorBarTooltip()
        {
            if (this.RecID <= 0)
            {
                this.btnBottom.ToolTipText = "定位到末页";
                this.btnTop.ToolTipText = "定位到首页";
                this.btnNext.ToolTipText = "定位到下一页";
                this.btnPrev.ToolTipText = "定位到前一页";
            }
            else
            {
                this.btnBottom.ToolTipText = "定位到末记录";
                this.btnTop.ToolTipText = "定位到首记录";
                this.btnNext.ToolTipText = "定位到下一条记录";
                this.btnPrev.ToolTipText = "定位到上一条记录";
            }
        }

        private void dgList_DefineColumn(object sender, EventArgs e)
        {
            base.SelectListViewField(dgList);
        }
        private void dgList_KeyDown(object sender, KeyEventArgs e)
        {

        }
        private void dgList_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (dgList.CurrentRow != null && BaseFunctions.IsDataGridCell(this.dgList, e))
            {
                this.RecID = Convert.ToInt64(dgList.RecID);
            }
        }

        protected override void Field_Leave(object sender, System.EventArgs e)
        {
            base.Field_Leave(sender, e);
            Control con = sender as Control;
            if (con == null) return;

            //below is some speci field , need do some speci work
            if (  con.Name == txtMarketCost.Name &&   CvtFunc.ToDouble(txtPlanCost.Text) == 0 && (this.formStatus == FormStatus.AddNew || this.formStatus == FormStatus.Update))
            {
                txtPlanCost.Text = txtMarketCost.Text;
            }
        }
        protected override void Field_Change(object sender, EventArgs e)
        {
            base.Field_Change(sender, e);
            if (this.formStatus == FormStatus.Delete) return;
            Control con = sender as Control;
            if (con == null) return;
            if (con.Name.ToUpper() == txtTreatCost.Name.ToUpper() && (this.formStatus == FormStatus.AddNew  || this.formStatus == FormStatus.Update ))
            {
                if (txtItemNo.Text == "") return;
                //
                DBAccess mdbcon = new DBAccess(false, false);
                string strSQL="update iminvmaster set TreatCost='"+ CvtFunc.ToDouble(txtTreatCost.Text) +"' where recid ='"+ this.RecID  +"'";
                mdbcon.ExecuteSql(strSQL);
 
                strSQL ="select RecStamp from " + this.TableName + " where RecID='" + this.RecID + "'";
                DataRow drRow = mdbcon.GetDataFirstRow(strSQL);
                if (drRow != null)
                {
                    this.TimeStamp = (byte[])drRow["RecStamp"];
                }
               
                
                //
               
                {
                    #region create table
                    DataFunctions.DelTemporyTable(mdbcon, "#rmWKCalDict");
                        strSQL = @" CREATE TABLE [#rmWKCalDict](
	                    [RecID] [int] IDENTITY(1,1) NOT NULL,
	                    [SeqNo] [int] NOT NULL  DEFAULT ((0)),
	                    [RecStamp] [timestamp] NULL,
	                    [CHNFieldName] [varchar](50) DEFAULT ('‘’'),
	                    [SYSFieldName] [varchar](50) DEFAULT (''),
	                    [SYSTableName] [varchar](50) NOT NULL DEFAULT (''),
	                    [Type] [varchar](50) NOT NULL  DEFAULT (''),
	                    [Description] [varchar](500)  NOT NULL  DEFAULT ('')
                    )";
                    mdbcon.ExecuteSql(strSQL);

                    strSQL = @" INSERT INTO #rmWKCalDict( CHNFieldName,Description,SysFieldName,SysTableName)
                       VALUES ('{0}','{1}','{2}','{3}')";
                    string strSQLTmp = string.Format(strSQL, "常用单价", "", "TreatCost", "Iminvmaster");
                    mdbcon.ExecuteSql(strSQLTmp);
                    strSQLTmp = string.Format(strSQL, "长度", "", "prodLength", "Iminvmaster");
                    mdbcon.ExecuteSql(strSQLTmp);
                    strSQLTmp = string.Format(strSQL, "宽度", "", "prodWidth", "Iminvmaster");
                    mdbcon.ExecuteSql(strSQLTmp);
                    strSQLTmp = string.Format(strSQL, "高度", "", "prodHeight", "Iminvmaster");
                    mdbcon.ExecuteSql(strSQLTmp);
                    strSQLTmp = string.Format(strSQL, "克重", "", "GramWeight", "Iminvmaster");
                    mdbcon.ExecuteSql(strSQLTmp);
                    strSQLTmp = string.Format(strSQL, "单张纸厚度", "", "PaperHeight", "Iminvmaster");
                    mdbcon.ExecuteSql(strSQLTmp);
                    strSQL = "select * from #rmWKCalDict";
                    #endregion
                    //用来检查表达式
                    string strWKFormula = txtPriceFormula.Text;
                    if (strWKFormula != "" && m_lRecId>0)
                    {
                        strSQL = "select * from #rmWKCalDict";
                        DataTable dtDict = mdbcon.GetDataTable(strSQL);
                        foreach (DataRow drDict in dtDict.Rows)
                        {
                            strWKFormula = strWKFormula.Replace(CvtFunc.ToString(drDict["CHNFieldName"]), CvtFunc.ToString(drDict["SYSTableName"]) + "." + CvtFunc.ToString(drDict["SYSFieldName"]));
                        }
                        
                        strSQL = @" select top 1 {0}   from iminvmaster where recid='{1}'";
                        strSQL = string.Format(strSQL, strWKFormula, m_lRecId.ToString());
                        try
                        {
                            DataRow drQty = mdbcon.GetDataFirstRow(strSQL);
                            txtMarketCost.Text = BaseFunctions.FormatNumeric(CvtFunc.ToDouble(drQty[0]), "Ns.3");
                        }
                        catch (Exception ex)
                        {
                            //MessageBox.Show(ex.ToString());
                            MessageBox.Show("表达示错误，请检查后重新输入。", SysVar.WarnTitle);
                            return;
                        }
                        
                    }

                }
                if (txtPriceFormula.Text == "" && (this.formStatus == FormStatus.AddNew || this.formStatus == FormStatus.Update ) )
                {
                    txtMarketCost.Text = txtTreatCost.Text;
                    txtCostUnit.Text = txtTreatCostUnit.Text;                    
                }
                if ((txtPlanCost.Text == "" || CvtFunc.ToDouble(  txtPlanCost.Text )==0)  && (this.formStatus == FormStatus.AddNew || this.formStatus == FormStatus.Update))
                {
                    txtPlanCost.Text = txtTreatCost.Text;                   
                }
                strSQL = "update iminvmaster set PlanCost='" + CvtFunc.ToDouble(txtPlanCost.Text) + "',MarketCost='" + CvtFunc.ToDouble(txtMarketCost.Text) + "' where recid ='" + this.RecID + "'";
                mdbcon.ExecuteSql(strSQL);

                strSQL = "select RecStamp from " + this.TableName + " where RecID='" + this.RecID + "'";
                drRow = mdbcon.GetDataFirstRow(strSQL);
                if (drRow != null)
                {
                    this.TimeStamp = (byte[])drRow["RecStamp"];
                }
                mdbcon.CloseCon(); 
            }
            else if (con.Name == txtMaterialTypeID.Name && formStatus == FormStatus.Update  )
            {
                txtMaterialType.Text = DataFunctions.GetFieldValue ("rmMaterialType","MaterialType","MaterialTypeID='"+ txtMaterialTypeID.Text +"'");
            }
            else if (con.Name == txtSecondMaterialTypeID.Name && formStatus == FormStatus.Update)
            {
                txtSecondMaterialType.Text = DataFunctions.GetFieldValue ("rmSecondMaterialType","MaterialTypeName","MaterialTypeID='"+ txtSecondMaterialTypeID.Text +"'"); 
            }
            else if (con.Name == txtMarketCost.Name)
            {
                if (CvtFunc.ToDouble(DataFunctions.GetFieldValue("iminvmaster", "plancost", "recid='" + this.RecID + "'")) == 0)
                {
                    txtPlanCost.Text = txtMarketCost.Text;
                }
            }

          
        }
        protected override void Field_KeyPress(object sender, KeyPressEventArgs e)
        {
            base.Field_KeyPress(sender, e);
        }

        private void tbcMain_Selecting(object sender, TabControlCancelEventArgs e)
        {
            if ((this.formStatus == FormStatus.Query || this.formStatus == FormStatus.Delete) &&
                this.dgList.Rows.Count == 0 && e.TabPageIndex > 0)
            {
                e.Cancel = true;
                return;
            }

            if (e.TabPageIndex == 0)
            {
                if (this.formStatus == FormStatus.AddNew || this.formStatus == FormStatus.Update)
                {
                    if (this.ConfirmChange())
                    {
                        if (MessageBox.Show(SysVar.SaveChangeTitle, SysVar.WarnTitle, MessageBoxButtons.YesNo) == DialogResult.Yes)
                        {
                            if (!this.UpdateData())
                            {
                                if (m_bTabPageNeedCancel)
                                    e.Cancel = true;

                                m_bTabPageNeedCancel = true;
                                return;
                            }
                        }
                    }
                    this.formStatus = FormStatus.Delete;
                }
                else if (this.formStatus == FormStatus.Query)
                {
                    this.formStatus = FormStatus.Delete;
                }
                this.dgList.RefreshData();
                this.dgList.Focus();
            }
            else if (e.TabPageIndex != 0 && this.formStatus != FormStatus.AddNew)
            {
                if (this.RecID == -1)
                    this.RecID = Convert.ToInt64(dgList.RecID);

              
            }
        }
        private void tbcMain_DrawItem(object sender, DrawItemEventArgs e)
        {
            BaseFunctions.TabControl_DrawItem(sender, e, true);
        }
        private void FileMenu_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem mnuItem = sender as ToolStripMenuItem;
            if (mnuItem != null)
            {
                switch (mnuItem.Name)
                {
                    case "newToolStripMenuItem":
                        btnNew_Click(sender, e);
                        break;
                    case "cancelToolStripMenuItem":
                        btnCancel_Click(sender, e);
                        break;
                    case "deleteToolStripMenuItem":
                        btnDelete_Click(sender, e);
                        break;
                    case "saveToolStripMenuItem":
                        btnUpdate_Click(sender, e);
                        break;
                    case "exitToolStripMenuItem":
                        btnExit_Click(sender, e);
                        break;
                }
            }
        }

        #endregion Form Events***

        #region ***Form Functions

        public override bool UpdateData()
        {
            bool bUpdateResult = true;
            if (base.ConfirmChange())
            {
                bUpdateResult = base.UpdateData();
            }
            return bUpdateResult;
        }
        public override bool ConfirmChange()
        {
            return (base.ConfirmChange());
        }
        protected override bool FieldCheck(string strFieldValue, string strFieldName, ref string strErrPrompt)
        {

            strErrPrompt = string.Empty;
            DBAccess dBAccess = new DBAccess(false, false);
            DataRow dr = base.GetCurrentMtnDataRow();


            IM.BusinessRule.ImInvMasterBRL mBRL = new WP.IM.BusinessRule.ImInvMasterBRL();
            bool bCheckResult = mBRL.FieldCheck(dBAccess, dr, strFieldName, ref strErrPrompt, this.formStatus);
            dBAccess.CloseCon();
            return bCheckResult;

        }

        protected override void ubtLookUp_Click(object sender, EventArgs e)
        {
            Control con = sender as Control;
            if (con == null) return;
            if (con == this.ubtSecondMaterialType)
            {
                string strSql = string.Empty;

                //if (txtMaterialType.Text.Trim() == "")
                //{
                //    strSql = "select ParentMaterialID as 一级类别 	,MaterialTypeID as 二级类别代码	,MaterialTypeName as 二级类别名称,StandardCost as 常用单价	,StandardCostUnit as 单位 from rmSecondMaterialType ";
                //}
                //else
                {
                    //string strMaterialTypeID = DataFunctions.GetFieldValue("rmMaterialType", "MaterialTypeID", "MaterialType='" + txtMaterialType.Text + "'");
                    strSql = "select MaterialTypeID as 价格类别代码	,MaterialTypeName as 价格类别名称,StandardCost as 常用单价	,StandardCostUnit as 单位 from rmSecondMaterialType";
                }

                string strFindValue = txtSecondMaterialTypeID.Text;
                string strLookUpField = "MaterialTypeID";
                frmLookUp frmlookup = new frmLookUp(strSql, "", strFindValue, strLookUpField); ////, bNewEditEnabled);

                frmlookup.ShowDialog();
                if (frmlookup.HaveReturnValue)
                {   
                    txtSecondMaterialTypeID.Text = frmlookup.GetReturnValue("MaterialTypeID");
                    txtSecondMaterialType.Text = frmlookup.GetReturnValue("MaterialTypeName");
                    if (this.formStatus == FormStatus.AddNew || this.formStatus == FormStatus.Update)
                    {
                        if (MessageBox.Show("是否更改常用单价？", "", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.Yes)
                        {
                            txtTreatCost.Text = frmlookup.GetReturnValue("StandardCost");
                            txtCostUnit.Text = frmlookup.GetReturnValue("StandardCostUnit");
                            txtTreatCostUnit.Text = txtCostUnit.Text;
                            txtMarketCost.Text = txtTreatCost.Text;
                            txtPlanCost.Text = txtTreatCost.Text;
                            Field_Change(txtTreatCost, new EventArgs());
                        }
                    }
                }
                frmlookup.Close();

            }
            else 
                base.ubtLookUp_Click(sender, e);
        }

        protected override string GetLookUpSQL(string strTableName, string strLookUpControlName)
        {            
            return base.GetLookUpSQL(strTableName, strLookUpControlName);
        }
        public override void SetButtonStatus()
        {
            toolStripMenuItem1.Visible = true;
            switch (this.formStatus)
            {
                case FormStatus.AddNew:
                    BaseFunctions.ControlEnabled(this.toolStrip, false);
                    this.btnUpdate.Enabled = true;
                    this.btnDelete.Enabled = false;
                    this.btnNew.Enabled = false ;
                    this.btnCancel.Enabled = true;
                    this.btnFormula.Enabled = true;
                    break;
                case FormStatus.Delete:
                    BaseFunctions.ControlEnabled(this.toolStrip, false);
                    this.btnUpdate.Enabled = false;
                    this.btnDelete.Enabled = false;
                    this.btnNew.Enabled = ( false   && this.CurrentMenuInfo.strPermit == "Y");
                    this.btnCancel.Enabled = false;
                    //this.btnUpdatePlanCost.Enabled = true;
                    更新计划价格为基本单价价格ToolStripMenuItem.Enabled = true;
                    btnStatus.Enabled = true;
                    break;
                case FormStatus.Query:
                    BaseFunctions.ControlEnabled(this.toolStrip, false);
                    this.btnUpdate.Enabled = false;
                    this.btnDelete.Enabled = false;
                    this.btnNew.Enabled = (false && this.CurrentMenuInfo.strPermit == "Y");
                    this.btnCancel.Enabled = false;                    
                    break;
                case FormStatus.Update:
                    BaseFunctions.ControlEnabled(this.toolStrip, false);
                    this.btnUpdate.Enabled = true;
                    this.btnDelete.Enabled = false ;
                    this.btnNew.Enabled = false ;
                    this.btnCancel.Enabled = true;
                    btnRefreshPrice.Enabled = true;
                    更新BOM单价ToolStripMenuItem.Enabled = true;
                    btnCopyToNewVer.Enabled = true;
                    btnFormula.Enabled = true;
                    btnStatus.Enabled = false;
                    break;
                case FormStatus.Loading:
                    break;

            }

            this.btnToExcel.Visible = (this.formStatus == FormStatus.Delete || this.formStatus == FormStatus.Query) && SysVar.AbleToExcel;
            this.btnToExcel.Enabled = this.formStatus == FormStatus.Delete || this.formStatus == FormStatus.Query;

            newToolStripMenuItem.Enabled = btnNew.Enabled;
            cancelToolStripMenuItem.Enabled = btnCancel.Enabled;
            deleteToolStripMenuItem.Enabled = btnDelete.Enabled;
            saveToolStripMenuItem.Enabled = btnUpdate.Enabled;

            this.btnTop.Enabled = true;
            this.btnBottom.Enabled = true;
            this.btnPrev.Enabled = true;
            this.btnNext.Enabled = true;
            this.btnHelp.Enabled = true;
            this.btnExit.Enabled = true;
            this.btnCopyToNewVer.Visible = false;

            if (this.formStatus == FormStatus.Query || this.formStatus == FormStatus.Delete)
            {
                this.更新计划价格为基本单价价格ToolStripMenuItem.Enabled = true;
                this.tsCboMaterialType.Enabled = true;
                this.toolStripLabel1.Enabled = true;
                this.toolStripLabel2.Enabled = true;
                this.tsCboSecondMaterialType.Enabled = true; 

                btnStatus.Enabled = true;
                toolStripMenuItem1.Enabled = true;
            }
            else
            {
                this.更新计划价格为基本单价价格ToolStripMenuItem.Enabled = false;
                this.tsCboMaterialType.Enabled = false ;
                this.toolStripLabel1.Enabled = false ;
                this.toolStripLabel2.Enabled = false;
                this.tsCboSecondMaterialType.Enabled = false;
                btnStatus.Enabled = false;
                toolStripMenuItem1.Enabled = false ;
            }
            btnRefreshPrice.Enabled = true;
            newToolStripMenuItem.Enabled = this.btnNew.Enabled;
        }
        public override void SetOtherStatus()
        {
            mblnSettingStatus = true;

            switch (this.formStatus)
            {
                case FormStatus.AddNew:
                    this.txtItemNo.Focus();
                    break;
                case FormStatus.Delete:
                    break;
                case FormStatus.Query:
                    break;
                case FormStatus.Update:
                    break;
                case FormStatus.Loading:
                    break;
            }

            mblnSettingStatus = false;
        }
        public override void RefreshOverView()
        {
            base.RefreshOverView();
            if (this.RecID != -1)
                this.dgList.RecID = this.RecID;
        }

        private void ShowOverViewGrid(string strWhereCondition)
        {
            string strSql = "";
            if (dgList.Sql.Trim() == "")
                strSql = WP.Commons.BaseFunctions.GetLookUpSQL(this.TableName, this.CurrentMenuInfo.iParameter);
            else
                strSql = dgList.Sql;

            if (strWhereCondition != "")
            {
                string strOrderBy = BaseFunctions.GetSqlParts(strSql, SqlOption.SqlPartOrderBy);
                strSql = BaseFunctions.GetSqlParts(strSql, SqlOption.SqlPartMain) + " where " + strWhereCondition;
                strSql += strOrderBy;
            }
            //string strWhere = BaseFunctions.GetSqlParts(strSql, SqlOption.SqlPartWhere);
            //mstrWhereCondition = strWhere;
            this.dgList.Sql = strSql;
        }

        private void FillLookUpInfo()
        {
            SetFieldLookUpInfo("SupNo", "apSupplier", "SupNo", "ubtSupNo");
            SetFieldLookUpInfo("SupName", "apSupplier", "SupName", "ubtSupName");
            SetFieldLookUpInfo("MaterialTypeID", "rmMaterialType", "MaterialTypeID", "ubtMaterialType");
            SetFieldLookUpInfo("MaterialType", "rmMaterialType", "MaterialType", "ubtMaterialType");
            SetFieldLookUpInfo("SecondMaterialTypeID", "rmSecondMaterialType", "MaterialTypeTypeID", "ubtSecondMaterialType");
            SetFieldLookUpInfo("SecondMaterialType", "rmSecondMaterialType", "MaterialTypeName", "ubtSecondMaterialType");            
        }

        #endregion Form Functions***

        private void btnRefreshPrice_Click(object sender, EventArgs e)
        {
            DBAccess dbcon = new DBAccess(false, false);
            dbcon.BeginTran();
            
            dbcon.CloseCon();
            MessageBox.Show("更新完成！", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void btnUpdateBOMPrice_Click(object sender, EventArgs e)
        {
            if (!UpdateData()) return;
            string strItemNo = CvtFunc.ToString(this.dgList.CurrentRow.Cells["ItemNo"].Value );    //txtItemNo.Text ;
            string strSupNo = CvtFunc.ToString(this.dgList.CurrentRow.Cells["SupNo"].Value);    //txtSupNo.Text ;
            DBAccess dbcon = new DBAccess ( false,false );
            string strSQL = "select * from iminvmaster where itemno='" + strItemNo + "' and supno='" + strSupNo + "'";
            DataRow drItem = dbcon.GetDataFirstRow ( strSQL );
            if (drItem != null)
            {
                DataFunctions.UpdateBOMCOSTByItem(dbcon,  drItem);
            }
            dbcon.CloseCon();
            MessageBox.Show("更新完成！", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void btnFormula_Click(object sender, EventArgs e)
        {
            //if (this.m_lRecId <= 0)
            //{
                if (!UpdateData()) return; 
            //}
            frmItemPriceFormula frmFormula = new frmItemPriceFormula();
            frmFormula.Text = "转换系数设置";
            double dblPrice = 0;
            string strPriceFormula = txtPriceFormula.Text;
            if (frmFormula.ShowFormula(ref strPriceFormula, ref  dblPrice, this.m_lRecId.ToString ()))
            {
                txtPriceFormula.Text = strPriceFormula;
                txtMarketCost.Text = dblPrice.ToString("f6");
                
            }
        }

        private double GetMarketCost( DBAccess dbcon,  DataRow drRow)
        {
            double dblPrice = 0;
             
            string strSQL = @" select top 1 {0}   from iminvmaster where recid='{1}'";
            strSQL = string.Format(strSQL, drRow["PriceFormula"], drRow["RecID"] );
            try
            {
                DataRow drQty = dbcon.GetDataFirstRow(strSQL);
                dblPrice = CvtFunc.ToDouble(drQty[0]);
            }
            catch (Exception ex)
            {
                return 0;
            }
            return dblPrice;
        }

        private void btnCopyToNewVer_Click(object sender, EventArgs e)
        {
            frmCopyItem frmCopy = new frmCopyItem();
            string strNewItemNo ="";
            string strNewSupName ="";
            string strOldRecID = this.m_lRecId.ToString();
            if (frmCopy.ShowCopyItem(ref strNewItemNo, ref strNewSupName))
            {
                this.btnNew_Click(sender, new EventArgs());
                txtItemNo.Text = strNewItemNo;
                txtSupName.Text = strNewSupName;
                DBAccess dbcon = new DBAccess ( false,false );
                IM.DataAccess.ImInvMasterDAL imDAL = new WP.IM.DataAccess.ImInvMasterDAL ();

                try
                {
                    string strSQL = "select * from iminvmaster where RecID='" + strOldRecID + "'";
                    DataRow drItemNo = dbcon.GetDataFirstRow(strSQL);
                    DataRow drNewItem = dbcon.GetDataTable(strSQL).NewRow();
                    if (drItemNo != null)
                    {
                        foreach (DataColumn drCol in drItemNo.Table.Columns)
                        {
                            if (drCol.ToString().Trim().ToUpper() != "RECID" && drCol.ToString().Trim().ToUpper() != "ITEMNO"
                                 && drCol.ToString().Trim().ToUpper() != "SUPNAME" && drCol.ToString().Trim().ToUpper() != "RECSTAMP")
                            {
                                drNewItem[drCol.ToString()] = drItemNo[drCol.ToString()];
                            }
                        }
                        drNewItem["ItemNo"] = strNewItemNo;
                        drNewItem["SupName"] = strNewSupName;
                        strSQL = "select MaterialTypeID	,MaterialTypeName ,StandardCost	,StandardCostUnit  from rmSecondMaterialType where MaterialTypeName='" + CvtFunc.ToString(drNewItem["SecondMaterialType"]) + "'";
                        DataRow drCatePrice = dbcon.GetDataFirstRow(strSQL);
                        if (drCatePrice != null)
                        {
                             drNewItem["MarketCost"] =drCatePrice["StandardCost"];
                             drNewItem["CostUnit"] = drCatePrice["StandardCostUnit"];
                             drNewItem["TreatCost"] = drCatePrice["StandardCost"];
                             drNewItem["PlanCost"] = drCatePrice["StandardCost"];
                        }
                        DataFunctions.UpdateTable(dbcon, imDAL.Fields, "iminvmaster", drNewItem, FormStatus.AddNew);                       
                    }
                    
                    strOldRecID = CvtFunc.ToString(drNewItem["RecID"]);
                    //this.btnUpdate_Click(sender, new EventArgs());
                   
                    DataRow dr = dbcon.GetDataFirstRow("select top 1 * from " + this.TableName + " where RecID='"+ strOldRecID +"'");
                    if (dr != null)
                    {
                        this.TimeStamp = (byte[])dr["RecStamp"];
                        BaseFunctions.FillUIControlByDataRow(this.arrayUpdatecontrols, dr);
                    }
                    this.formStatus = FormStatus.Update;
                    this.RefreshOverView();
                    if (dgList.CurrentRow != null)
                    {
                        this.RecID = Convert.ToInt64(strOldRecID);
                    }
                     base.RefershData();
                    this.dgList.FindRecord(strOldRecID, "RecID");
                    dbcon.CloseCon();
                    Field_Change(txtTreatCost, new EventArgs());
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
        }

        private void btnUpdatePlanCost_Click(object sender, EventArgs e)
        {
            DBAccess dbcon = new DBAccess(false, false);
            if (MessageBox.Show("是否更新所有的计划单价？", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                string strSQL = "update iminvmaster set plancost=MarketCost ";
                dbcon.ExecuteSql(strSQL);
                dbcon.CloseCon();
                MessageBox.Show("更新完成！", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                base.RefershData();
                base.RefreshOverView();
                this.dgList.RefreshData(); 
            }
        }

        private void tsCboMaterialType_SelectedIndexChanged(object sender, EventArgs e)
        {
            string strMaterialTypeID = "";
            string strCond = "";
            if (tsCboMaterialType.SelectedItem.ToString() == "")
            {
                strCond = "1=1";
            }
            else
            {
                strMaterialTypeID = BaseFunctions.Split(tsCboMaterialType.SelectedItem.ToString(), " - ")[0];
                if (strMaterialTypeID == "") return;
                strCond = "materialtypeID='" + strMaterialTypeID + "'";
            }
            if (tsCboSecondMaterialType.SelectedItem!=null && tsCboSecondMaterialType.SelectedItem.ToString() != "")
            {
                string strSecondMaterialTypeID = BaseFunctions.Split(tsCboSecondMaterialType.SelectedItem.ToString(), " - ")[0];
                strCond += " and SecondMaterialTypeID='" + strSecondMaterialTypeID + "'";
            }
            ShowOverViewGrid( strCond );
            tsCboSecondMaterialType.SelectedItem   = "" ;            
        }

        private void tsCboMaterialType_DropDown(object sender, EventArgs e)
        {

        }

        private void AllowToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowOverViewGrid("ClosedStatus='0'");
        }

        private void ClosedToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowOverViewGrid("ClosedStatus='1'");
        }

        private void allToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowOverViewGrid("ClosedStatus='0' or ClosedStatus='1'");
        }

        private void 更新常用单价为类别单价ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!UpdateData()) return;
            string strItemNo = txtItemNo.Text;
            string strSupNo = txtSupNo.Text;
            string strMaterialType = txtMaterialType.Text;
            string strSecondMaterialType = txtSecondMaterialType.Text;
            WP.IM.DataAccess.ImInvMasterDAL imDAL = new WP.IM.DataAccess.ImInvMasterDAL ();
            
            DBAccess dbcon = new DBAccess(false, false);            
            {
                dbcon.BeginTran();
                if (imDAL.UpdateTreatCostToSecondMaterialType(dbcon))
                {
                    dbcon.CommitTran();
                    MessageBox.Show("更新完成！", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    dbcon.RollbackTran();
                }
            }
            dbcon.CloseCon();
            this.RefreshOverView();
            this.dgList.RefreshData();
        }

        private void tsCboSecondMaterialType_SelectedIndexChanged(object sender, EventArgs e)
        {
            string strMaterialTypeID = "";
            string strCond = "";
            if ( tsCboMaterialType.SelectedItem ==null || tsCboMaterialType.SelectedItem.ToString() == "")
            {
                strCond = "1=1";
            }
            else
            {
                strMaterialTypeID = BaseFunctions.Split(tsCboMaterialType.SelectedItem.ToString(), " - ")[0];
                if (strMaterialTypeID == "") return;
                strCond = "materialtypeID='" + strMaterialTypeID + "'";
            }
            if (tsCboSecondMaterialType.SelectedItem != null && tsCboSecondMaterialType.SelectedItem.ToString() != "")
            {
                string strSecondMaterialTypeID = BaseFunctions.Split(tsCboSecondMaterialType.SelectedItem.ToString(), " - ")[0];
                strCond += " and SecondMaterialTypeID='" + strSecondMaterialTypeID + "'";
            }
            ShowOverViewGrid(strCond);
            //tsCboSecondMaterialType.SelectedItem = "";                 
        }

        private void btnUpdateToMarketCost_Click(object sender, EventArgs e)
        {
            txtPlanCost.Text = txtMarketCost.Text;
        }
        
      

    }
}
